package com.example.nsddemo

import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.Socket
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.RejectedExecutionException

class ServiceCommunicationActivity : AppCompatActivity() {
    companion object {
        const val EXTRA_HOST = "extra_host"
        const val EXTRA_PORT = "extra_port"
        const val EXTRA_SERVICE_NAME = "extra_service_name"
        const val SERVICE_TYPE = "SERVICE_TYPE"
        const val SERVICE_VERSION = "SERVICE_VERSION"
        const val DEVICE_MODEL = "DEVICE_MODEL"

        private const val TAG = "ServiceCommunication"

        private const val STATUS_DISCONNECTED = 0
        private const val STATUS_CONNECTING = 1
        private const val STATUS_CONNECTED = 2
    }

    private lateinit var deviceNameTextView: TextView
    private lateinit var serviceTypeTextView: TextView
    private lateinit var versionTextView: TextView
    private lateinit var deviceModelTextView: TextView
    private lateinit var deviceInfoTextView: TextView
    private lateinit var connectionStatusTextView: TextView
    private lateinit var connectionStatusIndicator: TextView
    private lateinit var messageEditText: EditText
    private lateinit var sendButton: Button
    private lateinit var chatTextView: TextView

    private var socket: Socket? = null
    private var output: PrintWriter? = null
    private var input: BufferedReader? = null
    private var messageExecutor: ExecutorService? = null
    private var listeningExecutor: ExecutorService? = null

    private var host: String = ""
    private var port: Int = 0
    private var serviceName: String = ""
    private var serviceType: String = ""
    private var version: String = ""
    private var deviceModel: String = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_service_communication)

        host = intent.getStringExtra(EXTRA_HOST) ?: ""
        port = intent.getIntExtra(EXTRA_PORT, 0)
        serviceName = intent.getStringExtra(EXTRA_SERVICE_NAME) ?: "Unknown"
        serviceType = intent.getStringExtra(SERVICE_TYPE) ?: "Unknown"
        version = intent.getStringExtra(SERVICE_VERSION) ?: "Unknown"
        deviceModel = intent.getStringExtra(DEVICE_MODEL) ?: "Unknown"

        if (host.isEmpty() || port == 0) {
            Toast.makeText(this, "无效的服务信息", Toast.LENGTH_SHORT).show()
            finish()
            return
        }

        initViews()
        setupClickListeners()
        updateConnectionStatus(STATUS_DISCONNECTED)
        connectToService()
    }

    private fun initViews() {
        deviceNameTextView = findViewById(R.id.deviceNameTextView)
        serviceTypeTextView = findViewById(R.id.serviceTypeTextView)
        versionTextView = findViewById(R.id.versionTextView)
        deviceModelTextView = findViewById(R.id.deviceModelTextView)
        deviceInfoTextView = findViewById(R.id.deviceInfoTextView)
        connectionStatusTextView = findViewById(R.id.connectionStatusTextView)
        connectionStatusIndicator = findViewById(R.id.connectionStatusIndicator)
        messageEditText = findViewById(R.id.messageEditText)
        sendButton = findViewById(R.id.sendButton)
        chatTextView = findViewById(R.id.chatTextView)

        // 初始化设备信息
        deviceNameTextView.text = serviceName
        deviceInfoTextView.text = "IP: $host | 端口: $port"
        serviceTypeTextView.text = "SERVICE_TYPE: $serviceType"
        versionTextView.text = "VERSION: $version"
        deviceModelTextView.text = "设备型号: $deviceModel"
    }

    private fun setupClickListeners() {
        sendButton.setOnClickListener {
            val message = messageEditText.text.toString().trim()
            if (message.isNotEmpty()) {
                sendMessage(message)
                messageEditText.text.clear()
            } else {
                Toast.makeText(this, "请输入消息", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun updateConnectionStatus(status: Int) {
        when (status) {
            STATUS_DISCONNECTED -> {
                connectionStatusTextView.text = "连接状态: 已断开"
                connectionStatusIndicator.background = ContextCompat.getDrawable(this, R.drawable.connection_status_disconnected)
            }
            STATUS_CONNECTING -> {
                connectionStatusTextView.text = "连接状态: 连接中"
                connectionStatusIndicator.background = ContextCompat.getDrawable(this, R.drawable.connection_status_connecting)
            }
            STATUS_CONNECTED -> {
                connectionStatusTextView.text = "连接状态: 已连接"
                connectionStatusIndicator.background = ContextCompat.getDrawable(this, R.drawable.connection_status_connected)
            }
        }
    }

    private fun connectToService() {
        messageExecutor = Executors.newSingleThreadExecutor()
        listeningExecutor = Executors.newSingleThreadExecutor()

        updateConnectionStatus(STATUS_CONNECTING)

        messageExecutor?.execute {
            try {
                Log.d(TAG, "尝试连接到 $host:$port")
                socket = Socket(host, port)
                Log.d(TAG, "Socket 创建成功")

                output = PrintWriter(socket?.getOutputStream(), true)
                input = BufferedReader(InputStreamReader(socket?.getInputStream()))

                Log.d(TAG, "IO 流初始化成功")

                runOnUiThread {
                    updateConnectionStatus(STATUS_CONNECTED)
                    Toast.makeText(this@ServiceCommunicationActivity, "连接成功", Toast.LENGTH_SHORT).show()
                }

                // 使用单独的线程监听服务器消息
                listeningExecutor?.execute {
                    listenForMessages()
                }

            } catch (e: Exception) {
                Log.e(TAG, "连接失败", e)
                runOnUiThread {
                    updateConnectionStatus(STATUS_DISCONNECTED)
                    Toast.makeText(this@ServiceCommunicationActivity, "连接失败: ${e.message}", Toast.LENGTH_LONG).show()
                }
            }
        }
    }

    private fun sendMessage(message: String) {
        Log.d(TAG, "准备发送消息: $message")

        val currentExecutor = messageExecutor
        if (currentExecutor == null) {
            Log.e(TAG, "ExecutorService 为空")
            runOnUiThread {
                Toast.makeText(this, "发送失败: 线程池不可用", Toast.LENGTH_SHORT).show()
            }
            return
        }

        try {
            currentExecutor.execute {
                try {
                    Log.d(TAG, "在线程中发送消息: $message")

                    // 检查输出流是否可用
                    val currentOutput = output
                    if (currentOutput == null) {
                        Log.e(TAG, "输出流为空")
                        runOnUiThread {
                            Toast.makeText(this@ServiceCommunicationActivity, "发送失败: 输出流不可用", Toast.LENGTH_SHORT).show()
                        }
                        return@execute
                    }

                    // 检查 socket 是否连接
                    val currentSocket = socket
                    if (currentSocket?.isConnected != true) {
                        Log.e(TAG, "Socket 未连接")
                        runOnUiThread {
                            Toast.makeText(this@ServiceCommunicationActivity, "发送失败: 未连接到服务器", Toast.LENGTH_SHORT).show()
                        }
                        return@execute
                    }

                    currentOutput.println(message)
                    currentOutput.flush() // 强制刷新输出流
                    Log.d(TAG, "消息已发送: $message")

                    runOnUiThread {
                        appendToChat("我: $message")
                        Log.d(TAG, "消息已添加到聊天界面")
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "发送消息失败", e)
                    runOnUiThread {
                        Toast.makeText(this@ServiceCommunicationActivity, "发送失败: ${e.message}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        } catch (e: RejectedExecutionException) {
            Log.e(TAG, "任务提交被拒绝", e)
            runOnUiThread {
                Toast.makeText(this@ServiceCommunicationActivity, "发送失败: 任务提交被拒绝", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Log.e(TAG, "执行任务时异常", e)
            runOnUiThread {
                Toast.makeText(this@ServiceCommunicationActivity, "发送失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun listenForMessages() {
        try {
            Log.d(TAG, "开始监听服务器消息")

            val currentInput = input
            if (currentInput == null) {
                Log.e(TAG, "输入流为空")
                return
            }

            var line: String?
            while (true) {
                try {
                    line = currentInput.readLine()
                    if (line == null) {
                        Log.d(TAG, "服务器连接已断开")
                        runOnUiThread {
                            updateConnectionStatus(STATUS_DISCONNECTED)
                            Toast.makeText(this@ServiceCommunicationActivity, "服务器连接已断开", Toast.LENGTH_SHORT).show()
                        }
                        break
                    }

                    Log.d(TAG, "收到服务器消息: $line")
                    runOnUiThread {
                        appendToChat("对方: $line")
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "读取消息时异常", e)
                    runOnUiThread {
                        updateConnectionStatus(STATUS_DISCONNECTED)
                        Toast.makeText(this@ServiceCommunicationActivity, "读取消息异常: ${e.message}", Toast.LENGTH_SHORT).show()
                    }
                    break
                }
            }
            Log.d(TAG, "消息监听结束")
        } catch (e: Exception) {
            Log.e(TAG, "接收消息异常", e)
            runOnUiThread {
                updateConnectionStatus(STATUS_DISCONNECTED)
                Toast.makeText(this@ServiceCommunicationActivity, "接收消息异常: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun appendToChat(message: String) {
        try {
            val currentText = chatTextView.text.toString()
            val newText = if (currentText.isEmpty()) message else "$currentText\n$message"
            chatTextView.text = newText
            Log.d(TAG, "聊天内容已更新: $message")
        } catch (e: Exception) {
            Log.e(TAG, "更新聊天界面失败", e)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            Log.d(TAG, "关闭连接")
            input?.close()
            output?.close()
            socket?.close()
            Log.d(TAG, "连接已关闭")
        } catch (e: Exception) {
            Log.e(TAG, "关闭连接异常", e)
        }

        try {
            messageExecutor?.shutdown()
            listeningExecutor?.shutdown()
            Log.d(TAG, "线程池已关闭")
        } catch (e: Exception) {
            Log.e(TAG, "关闭线程池异常", e)
        }
    }
}
